//业绩明细页面
var $orderTable = $('#orderTableList');
// 表格高度
var globalHeight;
let accountId;
//防止表头与表格不对齐
$(window).resize(function () {
    $orderTable.bootstrapTable('resetView');
});
$(function () {
    globalHeight = $(window).height() - $('#orderTableList').offset().top - 30 - 25;
    var iframe=getIframeByElement(document.body);
    var iframeObj=$(iframe);
    let iframeSrc=iframeObj.attr("src");
    accountId=iframeSrc.substring(iframeSrc.indexOf('=')+1,iframeSrc.indexOf('&'));
    var userName=iframeSrc.substr(iframeSrc.indexOf('=',iframeSrc.indexOf('&'))+1);
    $("#userName").text(userName?userName+'的':'');
    //初始化订单列表
    orderTableListInit();
    $('#yearSelect').datepicker({
        language: 'zh-CN',
        startView: 'decade',
        endView: 'decade',
        maxViewMode: 'decade',
        minViewMode: 'decade',
        format: 'yyyy',
        autoclose:true,
        clearBtn:true,
        todayHighlight: true
    });
    $('#yearSelect').on('changeDate',function(){
        var yearDate = $('#yearSelect').val();
        if (yearDate.length!=4) {
            $('#monthSelect').val('');
            $("#moneyTotal").hide();
            $('#monthSelect').datepicker('destroy');
            $('#monthSelect').attr({'disabled':'disabled'});
        }else{
            $('#monthSelect').removeAttr('disabled');
            $('#monthSelect').datepicker('destroy').datepicker({
                language: 'zh-CN',
                startView: 'month',
                endView: 'month',
                maxViewMode: 'year',
                minViewMode: 'year',
                format: 'mm',
                autoclose: true,
                clearBtn:true,
                todayHighlight: true
            });
        }
        orderTableListInit();

    });
    $('#monthSelect').on('changeDate',function(){
        var monthDate = $('#monthSelect').val();
        if (monthDate.length==0) {
            $("#moneyTotal").hide();
        }else{
            $("#moneyTotal").show();
            getAchievementMoney();
        }
        orderTableListInit();

    })
});

/**
 * 功能：缩放页面重绘table高度
 * */
$(window).resize(debounce(resizeTable, 500));
function resizeTable() {
    // 计算初始表格高度 = 浏览器高度 - 表格距浏览器顶部高度 - 主体底部padding+margin
    // 注：表格距浏览器顶部高度此处用最外层div获取，解决table垂直滚动时距离
    globalHeight = $(window).height() - $('.bootstrap-table').offset().top - 30 - 25;
    $('#orderTableList').bootstrapTable('resetView', {height: $("#monthSelect").val()?'':globalHeight});
}



/**
 * 订单列表 --分页列表页
 */
function orderTableListInit() {
    $("#monthSelect").val()?$("body").css({'overflow':'auto'}):$("body").css({'overflow':'hidden'});
    let url=$("#monthSelect").val()?'/returnMoney/selectMonthPerformanceDetails':'/returnMoney/selectPerformanceDetails'
    //先销毁表格
    $orderTable.bootstrapTable('destroy');
    $orderTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url:url,//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'create_tm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: $("#monthSelect").val()?false:true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderId',
        idField: 'productOrderId',
        pageSize: 100,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [100],//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        height: $("#monthSelect").val()?'':globalHeight,
        fixedColumns: true,     // 冻结列
        fixedRightNumber: 1,    // 右侧固定列
        columns: [
            {title: '订单编号', field: 'orderNumber', align: 'left', valign: 'middle', formatter: orderNumberFormat},
            {title: '产品名称', field: 'productName',align: 'left', valign: 'middle'},
            {title: '客户名称', field: 'customerName',align: 'left', valign: 'middle'},
            {title: '合同编号',field: 'contractNumber',align: 'left', valign: 'middle',formatter: contractNumberFormat},
            {title: '产品类型', field: 'productCategories', align: 'left', valign: 'middle'},
            {title: '到款金额', field: 'arriveMoney',align: 'right', valign: 'middle'},
            {title: '到款方式',field: 'arriveMethod',align: 'left', valign: 'middle'},
            {title: '发放提成', field: 'royaltyStatus',align: 'left', valign: 'middle'},
            {title: '业绩金额',field: 'scoreMoney',align: 'right', valign: 'middle'},
            {title: '到款日期', field: 'arriveTime', align: 'right', valign: 'middle'},
            {title: '流水号', field: 'serial',align: 'left', valign: 'middle'},
            {title: '录入人',field: 'userName',align: 'left', valign: 'middle'},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            $('#orderTableList').css({
                minWidth: $('#orderTableList').width()
            })
            // table列可拖动宽度
            // $('.JCLRgrips').remove();
            // $('#orderTableList').css({
            //     minWidth: $('#orderTableList').width()
            // }).colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0,11,],      // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            //     /*onResize: function () {
            //     }*/
            // });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}
function searchReturnMoneyList() {
    $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
}

/**
 * 点击订单编号跳转到订单详情
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function orderNumberFormat(value, row, index) {
    if(value == null) {
        value = '';
    }
    return '<a href="JavaScript:void(0);" onclick="orderNumberDetail(\''+row.orderId+ '\')">'+value+'</a>';
}

function  orderNumberDetail(productOrderId) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '订单详情',
        url : "/front/orderManager/orderDetail?productOrderId=" + productOrderId
    }, true);
}

/**
 * 点击合同编号跳转到合同详情
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contractNumberFormat(value, row, index) {
    if(value == null) {
        value = '';
    }
    return '<a href="JavaScript:void(0);"   onclick=\'contractNumberDetail(\"'+row.contractId+'")\'>'+value+'</a>';
}

function  contractNumberDetail(contractId) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '合同详情',
        url : "/front/contractManager/contractDetail?contractId=" + contractId +"&jumpBs=1"
    }, true);
}


function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //其他查询条件
    let yearVal=$('#yearSelect').val(),monthVal=$('#monthSelect').val();
    params.accountId = accountId;
    params.dateUnit = yearVal?(monthVal?'2':'1'):'';
    params.year = yearVal;
    params.month = monthVal;
    params.orderNumber = $("#userNameSearch").val();
    return params;
}

function getAchievementMoney(){
    let yearVal=$('#yearSelect').val(),monthVal=$('#monthSelect').val();
    $.ajax({
        url: '/returnMoney/sumScoreMoney',
        type: 'POST',
        dataType: "json",
        data: {
            "accountId":accountId,
            "dateUnit":yearVal?(monthVal?'2':'1'):'',
            "year":yearVal,
            "month":monthVal
        },
        success: (function (data) {
            if (data.code == '000000') {
                $("#achievementMoney").text(data.data)
            }
        }),
        error: (function () {
            $.alert("失败");
        })
    })
}
//导出数据
function exportDetailFun() {
    let yearVal=$('#yearSelect').val(),monthVal=$('#monthSelect').val();
    let dateUnit=yearVal?(monthVal?'2':'1'):'';
    var url = "/returnMoney/exportPerformanceDetails?accountId="+accountId+"&dateUnit="+dateUnit+"&year="+yearVal+"&month="+monthVal
    console.log(url)
    window.location.href=encodeURI(encodeURI(url));
}
function exportDetailFun(element) {
    let yearVal=$('#yearSelect').val(),monthVal=$('#monthSelect').val();
    let dateUnit=yearVal?(monthVal?'2':'1'):'';
    var url = "/returnMoney/exportPerformanceDetails?accountId="+accountId+"&dateUnit="+dateUnit+"&year="+yearVal+"&month="+monthVal+'&orderNumber='+$("#userNameSearch").val()
    url = encodeURI(url);
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);     // get请求，请求地址，是否异步
    xhr.responseType = 'blob';                    // 返回类型blob
    xhr.onload = function () {                    // 请求完成处理函数
        if (this.status === 200) {
            var blob = this.response;             // 获取返回值
            if (blob.type == 'application/json') {
                $.alert({
                    title: '失败提醒',
                    content: '系统异常，导出数据失败！',
                })
            } else {
                var time = new Date();
                var a = document.createElement('a');
                a.download = '业绩明细 ' + new Date(time).Format("yyyy-MM-dd hh_mm_ss") + '.xlsx';
                a.href = window.URL.createObjectURL(blob);
                a.click();
            }
        }
    };
    // 发送ajax请求
    xhr.send();
}